<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateStaffCardAPIRequest;
use App\Http\Requests\API\UpdateStaffCardAPIRequest;
use App\Models\StaffCard;
use App\Models\StaffOrder;
use App\Models\StaffInfo;
use App\Repositories\StaffCardRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class StaffCardController
 * @package App\Http\Controllers\API
 */

class StaffCardAPIController extends AppBaseController
{
    /** @var  StaffCardRepository */
    private $staffCardRepository;

    public function __construct(StaffCardRepository $staffCardRepo)
    {
        $this->staffCardRepository = $staffCardRepo;
    }

    /**
     * Display a listing of the StaffCard.
     * GET|HEAD /staffCards
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->staffCardRepository->pushCriteria(new RequestCriteria($request));
        $this->staffCardRepository->pushCriteria(new LimitOffsetCriteria($request));
        // $staffCards = $this->staffCardRepository->all();
        
        $staffCards = $this->staffCardRepository->paginate($request->limit);

        return $this->sendResponse($staffCards->toArray(), 'Staff Cards retrieved successfully');
    }

    /**
     * Display a listing of the StaffCard.
     * GET|HEAD /staffCards
     *
     * @param Request $request
     * @return Response
     */
    public function annualListByUid(Request $request)
    {
        $uid  = $request->input('uid');

        if (empty($uid)) {
            return $this->sendError('invalid uid.');
        }

        $user = StaffInfo::where('id', $uid)->first();
        if (empty($user)) {
            return $this->sendError('invalid user.');
        }


        $t = time();

        $cards = StaffCard::select([        
                                'id', 
                                'name', 
                                'sell_time_start',
                                'sell_time_end',
                                'valid_time_start', 
                                'valid_time_end'
                            ])
                            ->orWhere(function ($query) use ($t) {
                                    $query
                                    ->where('sell_time_start', '<=', $t)
                                    ->where('sell_time_end', '>=', $t);
                                })
                            ->orWhere(function ($query) use ($t) {
                                    $query
                                    ->where('valid_time_start', '<=', $t)
                                    ->where('valid_time_end', '>', $t);
                                })
                            // ->whereRaw('(sell_time_start <= ? AND sell_time_end >= ?) OR (valid_time_start <= ? AND valid_time_end > ?)',[$t, $t, $t, $t])
                            ->orderBy('valid_time_start')
                            ->get()
                            ->toArray();

        $data = [];
        foreach ($cards as $k => $card) {
            $order = StaffOrder::where('staff_id', $uid)
                                    ->where('card_id', $card['id'])
                                    ->where('status', 1)
                                    ->first();

            $card['date'] = date('Y', $card['valid_time_start']);
            $card['purchased'] = $order ? 1 : 0;

            if (!$order && ($card['valid_time_end'] < $t || $card['sell_time_start'] > $t)) {
                continue;
            }
            $data[] = $card;
        }

        return $this->sendResponse($data, 'Staff Cards retrieved successfully');
    }

    /**
     * Display a listing of the StaffCard.
     * GET|HEAD /staffCards
     *
     * @param Request $request
     * @return Response
     */
    public function monthListByUid(Request $request)
    {
        $uid = $request->input('uid');

        if (empty($uid)) {
            return $this->sendError('invalid uid.');
        }

        $user = StaffInfo::where('id', $uid)->first();
        if (empty($user)) {
            return $this->sendError('invalid user.');
        }

        $t = time();
        $cards = StaffCard::select(['valid_time_start'])
                            ->whereRaw('(sell_time_start <= ? AND sell_time_end >= ?) OR (valid_time_start <= ? AND valid_time_end > ?)',[$t, $t, $t, $t])
                            ->get()
                            ->toArray();
        $months = [];
        foreach ($cards as $card) {
            $year = date('Y', $card['valid_time_start']);
            $year_now = date('Y');
            for ($i=1; $i <= 12; $i++) { 
                $months[] = sprintf('%s%02d', $year, $i);
                // $months[] = sprintf('%s%02d', $year_now, $i);
            }
        }

        $months = array_unique($months);
        sort($months);

        $data = [];
        foreach ($months as $month) {
            $order = StaffOrder::where('staff_id', $uid)
                                    ->where('card_date', $month)
                                    ->where('status', 1)
                                    ->first();
            $data[] = [
                'id'   => 0,
                'name' => sprintf('%s月卡', $month),
                'date' => $month,
                'valid_time_start' => mktime(0, 0, 0, intval(substr($month, -2)), 1, substr($month, 0, 4) ),
                'valid_time_end' => mktime(23, 59, 59, intval(substr($month, -2))+1, 0, substr($month, 0, 4) ),
                'purchased' => $order ? 1 : 0,
            ];
        }
        
        return $this->sendResponse($data, 'Staff Cards retrieved successfully');
    }

    /**
     * Store a newly created StaffCard in storage.
     * POST /staffCards
     *
     * @param CreateStaffCardAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateStaffCardAPIRequest $request)
    {
        $input = $request->all();

        $staffCards = $this->staffCardRepository->create($input);

        return $this->sendResponse($staffCards->toArray(), 'Staff Card saved successfully');
    }

    /**
     * Display the specified StaffCard.
     * GET|HEAD /staffCards/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var StaffCard $staffCard */
        $staffCard = $this->staffCardRepository->findWithoutFail($id);

        if (empty($staffCard)) {
            return $this->sendError('Staff Card not found');
        }

        return $this->sendResponse($staffCard->toArray(), 'Staff Card retrieved successfully');
    }

    /**
     * Update the specified StaffCard in storage.
     * PUT/PATCH /staffCards/{id}
     *
     * @param  int $id
     * @param UpdateStaffCardAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateStaffCardAPIRequest $request)
    {
        $input = $request->all();

        /** @var StaffCard $staffCard */
        $staffCard = $this->staffCardRepository->findWithoutFail($id);

        if (empty($staffCard)) {
            return $this->sendError('Staff Card not found');
        }

        $staffCard = $this->staffCardRepository->update($input, $id);

        return $this->sendResponse($staffCard->toArray(), 'StaffCard updated successfully');
    }

    /**
     * Remove the specified StaffCard from storage.
     * DELETE /staffCards/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var StaffCard $staffCard */
        $staffCard = $this->staffCardRepository->findWithoutFail($id);

        if (empty($staffCard)) {
            return $this->sendError('Staff Card not found');
        }

        $staffCard->delete();

        return $this->sendResponse($id, 'Staff Card deleted successfully');
    }

}
